package com.financing.controller.user;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import com.alibaba.fastjson.JSONObject;
import com.financing.common.CONST;
import com.financing.components.payment.Gateway;
import com.financing.enums.invest.CouponRule;
import com.financing.model.Data;
import com.financing.model.invest.CouponLog;
import com.financing.model.invest.Deposit;
import com.financing.model.invest.Repay;
import com.financing.model.invest.Trade;
import com.financing.model.invest.Withdraw;
import com.financing.model.user.Staff;
import com.financing.model.user.User;
import com.financing.model.user.UserReferee;
import com.financing.service.agent.VisitService;
import com.financing.service.invest.CouponLogService;
import com.financing.service.invest.CouponService;
import com.financing.service.invest.TradeService;
import com.financing.service.system.LoggerService;
import com.financing.service.user.BankCardService;
import com.financing.service.user.StaffService;
import com.financing.service.user.TokenService;
import com.financing.service.user.UserService;
import com.financing.util.AES;
import com.financing.util.CheckUtils;
import com.financing.util.DateUtil;
import com.financing.util.Http;
import com.financing.util.Json;
import com.financing.util.MD5Util;
import com.financing.util.MailUtil;
import com.financing.util.Money;
import com.financing.util.MyCaptchaRender;
import com.financing.util.RandomCodeUtil;
import com.financing.util.Str;
import com.financing.util.WechatSign;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;

/**
 *  用户控制器
 * @since 2017-06-06
 * @author 无处不在的二叔
 */
public class UserController extends Controller {
	private static VisitService visit = new VisitService();
	private static UserService user = new UserService();
	private static StaffService staff = new StaffService();
	private static TradeService trade = new TradeService();
	private static LoggerService log = new LoggerService();
	private static TokenService app = new TokenService();
	private static CouponService coupon = new CouponService();
	private static BankCardService bankCard = new BankCardService();
	private static CouponLogService couponLog = new CouponLogService();
	private static final Logger logger = Logger.getLogger(UserController.class);

	/**
	 * 用户列表
	 */
	@Clear
	public void test() throws Exception{ 
		List<User> list = User.me.find("select id,mobile,real_name,code,bank_card,cert_num,create_time from user where is_bind_bank_card='1'");
		// 创建HSSFWorkbook对象(excel的文档对象)  
		HSSFWorkbook wb = new HSSFWorkbook();  
		
		// 建立新的sheet对象（excel的表单）  
		HSSFSheet sheet = wb.createSheet("用户渠道报表");  
		
		// 设置第一行标题内容
		HSSFRow row1=sheet.createRow(0);  
		int i = 0;
		for(String title : Arrays.asList(new String[] {"手机号","真实姓名","银行卡号","身份证","注册时间","充值金额","提现金额","待还金额"})) {
			HSSFCell c1=row1.createCell(i);  
			c1.setCellValue(title);  
			sheet.setColumnWidth(i,6000);
			i++;
		}
		
		// 设置详细内容
		i = 1;
		for(User u : list) {
			HSSFRow row=sheet.createRow(i++);				
			row.createCell(0).setCellValue(u.getMobile());   				
			row.createCell(1).setCellValue(u.getRealName()); 	
			row.createCell(2).setCellValue(u.getBankCard()); 
			row.createCell(3).setCellValue(u.getCertNum()); 
			if(u.getCreateTime()!=null) {
				row.createCell(4).setCellValue(DateUtil.format(u.getCreateTime()));
			}
			Deposit d = Deposit.me.findFirst("select sum(amount) amt from deposit where mobile=? and status='success'",u.getMobile());
			row.createCell(5).setCellValue(Money.get(d.get("amt"))); 
			Withdraw w = Withdraw.me.findFirst("select sum(amount) amt from withdraw where mobile=? and status='success'",u.getMobile());
			row.createCell(6).setCellValue(Money.get(w.get("amt")));  
			Repay r = Repay.me.findFirst("select sum(period_total) amt from repay where user_id=? and status='process'",u.getId());
			row.createCell(7).setCellValue(Money.get(r.get("amt"))); 
		}
		
	    // 输出Excel文件  
		HttpServletResponse response = getResponse();
	    OutputStream output = response.getOutputStream();  
	    response.reset();  
	    response.setHeader("Content-disposition", "attachment; filename="+DateUtil.getTimeStamp()+".xls");  
	    response.setContentType("application/msexcel");          
	    wb.write(output);  
	    output.close();  
	    renderNull();
		renderJson(Json.ok("操作成功！"));
	}	
	
	/**
	 * 用户列表
	 */
	public void list() throws Exception{ 
		User u = getAttr("user");
		int page = getParaToInt("page",1);
		int size = getParaToInt("size",10);
		Map<String, String> params = Data.flat(getParaMap());
		String agents = visit.getAgents(u.getId());
		params.put("userId", agents);
		Page<User> p = user.list(page,size,params);
		for(User temp : p.getList()) {
			Page<Trade> list = trade.findByUser(1, 1, temp.getId(), "all");
			if(list.getList().size()>0){
				temp.put("trade", list.getList().get(0));
			}
			temp.put("agent", staff.findByUserId(temp.getAgentId()));
			if(temp.getIsBindBankCard()==1) {
				temp.put("card", bankCard.findMainCard(temp.getId()));
			}
			temp.put("amt", temp.getAvailableAmount());
		}
		renderJson(Json.ok("数据获取成功！", Data.put("page",p)));
	}	
	 
	/**
	 * 用户登陆
	 */
	@Clear
	public void login() throws UnsupportedEncodingException { 
		int aes = getParaToInt("aes",1);
		String workcode = getPara("workcode");
		String mobile = getPara("mobile","");
		String password = getPara("password","");
		String type = getPara("type");
		Date now = new Date();
		
		// AES解密
		if(aes==1) {
			mobile = AES.decode(mobile);
			password = AES.decode(password);
		}
		
		// 后台工号-手机号转换
		if(Str.eq("backend", type) && Str.nb(workcode)) {
			Staff s = staff.findByWorkcode(workcode.toUpperCase());
			if(s!=null) {
				mobile =s.getMobile();
			}else {
				renderJson(Json.error("工号不正确！"));
				return;
			}	
		}
		
		User u = user.findByMobile(mobile);
		if(u!=null) {
			if(u.getErrorCount()<4 || now.compareTo(u.getErrorLockTime())>0) {
				if(Str.nb(mobile) && Str.nb(password)){
					try {
						
						// 进行用用户名和密码验证,如果验证不过会throw exception
						// User u = user.checkLogin(mobile,MD5Util.encrypt(password));
						UsernamePasswordToken upt = new UsernamePasswordToken(mobile, password, false, type);
				        Subject subject = SecurityUtils.getSubject();
				        subject.login(upt);
						u.setLoginTime(new Date()).setLoginType(type).setErrorCount(0).update();

						// 刷新用户token
						String token = app.refresh(u, type);
						setSessionAttr("userId", u.getId());
						CONST.removeAttr("verifyCode"+mobile);
						
						// 后台登陆需要判断是否是员工
						if(Str.eq("backend", type)) {
							if(staff.findByUserId(u.getId())!=null) {
								setSessionAttr("token2", token);
							}else {
								renderJson(Json.error("您不是员工身份，不可登陆！"));
								return;
							}
						}else {
							setSessionAttr("token", token);
						}

						// 敏感信息加密
						if(aes==1) {
							u.setMobile(AES.encode(u.getMobile()));
							u.setCertNum(AES.encode(u.getCertNum()));
							u.setBankCard(AES.encode(u.getBankCard()));
							u.setEmail(AES.encode(u.getEmail()));
						}
						
						// 日志记录
						log.build("登陆", "用户登陆", u.getId(), Str.eq("backend", type) ? "backend" : "user");

						renderJson(Json.ok("登陆成功！", Data.put("token",token,"info",u)));
						
					} catch (Exception e) {
						u.setErrorCount(u.getErrorCount()+1);
						if(u.getErrorCount()>=4) {
							u.setErrorLockTime(new Date(now.getTime()+43200000));
						}
						u.update();
						renderJson(Json.error("手机号或密码不正确！\n(剩余可尝试"+(5-u.getErrorCount())+"次)"));
					}
				}else{ 
					renderJson(Json.error("手机号或密码不能为空！"));
				}
			}else{   	
				renderJson(Json.error("错误次数已达上限，请在"+DateUtil.format(u.getErrorLockTime(), DateUtil.DATETIME_LOCAL_FORMAT)+"后重试！"));
			}
		}else{ 
			renderJson(Json.error("该用户不存在！"));
		}
	}
	
	/**
	 * 退出登陆
	 */
	public void logout() {
		String type = getPara("type","app");
		User u = getAttr("user");
		app.removeByMobile(u.getMobile(),type);
		if(Str.eq("backend", type)) {
			removeSessionAttr("token2");
		}else {
			removeSessionAttr("token");
		}
		// 日志记录
		log.build("退出", "用户退出", u.getId(), getPara("type","user"));
		renderJson(Json.ok("退出登陆成功！"));
	}	
	
	/**
	 * 生成推荐人链接
	 */
	public void refereeLink() {
		User u = getAttr("user");
		renderJson(Json.ok("链接生成成功！", Data.put("link", "/app/page/user-registerInvite?referee="+u.getMobile())));
	}	

	/**
	 * 检验token是否失效
	 */
	public void checkToken() {
		String token = getPara("token","");
		Ret ret = app.check(token);
		if(ret.isOk()) {
			renderJson(Json.ok("TOKEN校验成功！"));
		}else {
			renderJson(Json.error(ret.getStr("msg")));
		}
	}
	
	/**
	 * 获取用户信息
	 * @throws Exception 
	 */
	public void info() throws Exception {	
		User u = getAttr("user");
		if(Str.nb(getPara("userId"))){
			u = User.me.findById(getParaToInt("userId"));
		}
		u = user.getInfo(u.getId(),getParaToInt("aes",1));

		int amt = 0;
		int num = 0;
		for(CouponLog cl : couponLog.findEnable(u)) {
			// 投资红包金额
			if(Str.eq("tzhb", cl.getType())) {
				amt += cl.getAmount(); 
			}
			// 加息券张数
			if(Str.eq("jxq", cl.getType())) {
					num++;
			}
		}
		u.put("jxq", num);
		u.put("tzhb", amt);
		renderJson(Json.ok("信息获取成功！", Data.put("info", u)));
	}

	/**
	 * 获取用户收益
	 * @throws Exception 
	 */
	public void assets() throws Exception {
		
		User u = getAttr("user");
		// 已收收益 = 加息券收益 + 平台收益 + 投资红包收益 + 现金红包收益 + 体验金收益
		
		// 查询用户余额
		u = user.getInfo(u.getId(),getParaToInt("aes",getParaToInt("aes",1)));
		
		// 资产总额 = 账户余额+冻结金额+代收收益+代收本金
		// 已收收益 = 加息券收益 + 平台收益 + 投资红包收益 + 现金红包收益 + 体验金收益

		// 账户余额
		// double amount = Double.valueOf(u.getStr("amount"));
		
		// 账户可用余额
		double availableAmount = Double.valueOf(u.getStr("available_amount"));

		// 计算资产
		Map<String, Double> map = user.sumAllAssets(u.getId());
		
		// 冻结余额
		double freezebleAmount = Double.valueOf(u.getStr("freezeble_amount"));
		
		// 代收本金
		double readyAmount = Money.format(map.get("amount"));
		
		// 代收收益
		double readyInterest = Money.format(map.get("interest"));
		
		// 体验金
		double totalTyj = Money.format(map.get("total_tyj"));
		
		// 累计投资金额
		double alreadyAmount = Money.format(map.get("amount2"));
		
		// 累计投资总收益
		double alreadyInterest = Money.format(map.get("interest2"));
		
		// 累计已还款利息
		double alreadyInterest2 = Money.format(map.get("interests"));
		
		// 累计已还款利息
		double alreadyJxq = Money.format(map.get("jxq"));

		// 昨日收益
		double yesterdayBenefit = user.sumYesterdayBenefit(u.getId());
		
		// 资产总额
		double all_assets = Money.format(availableAmount + freezebleAmount + readyAmount + readyInterest + totalTyj);
		
		// 累计获取收益
		logger.warn("资产总额==="+all_assets+" 昨日收益==="+yesterdayBenefit+" 体验金==="+totalTyj+" 代收本金==="+readyAmount+"  代收收益==="+readyInterest+"  累计投资金额==="+alreadyAmount+" 累计投资收益==="+alreadyInterest);
	
		renderJson(Json.ok("信息获取成功！", 
			Data.put("all_assets",String.valueOf(all_assets),"yesterday_benefit",String.valueOf(yesterdayBenefit),
				"already_jxq",alreadyJxq,"already_interest2",alreadyInterest2,"info",u,"total_tyj",String.valueOf(totalTyj),
				"available_amount",String.valueOf(availableAmount),"freezeble_amount",String.valueOf(freezebleAmount),
				"ready_amount",String.valueOf(readyAmount),"ready_interest",String.valueOf(readyInterest),
				"already_amount",String.valueOf(alreadyAmount),"already_interest",String.valueOf(alreadyInterest))));
	}
	
	/** 
	 * 用户注册
	 * @throws Exception 
	 */
	@Clear
	public void reg1() throws Exception {
		int aes = getParaToInt("aes",1);
		String mobile = aes==1 ? AES.decode(getPara("mobile")) : getPara("mobile");
		String password = aes==1 ? AES.decode(getPara("password")) : getPara("password");
		String sms = getPara("sms");
		String referee = getPara("referee");
		String type = getPara("type","iOS");

		if(CheckUtils.checkPassword(password)){
			if(CheckUtils.checkMoible(mobile) && Str.nb(password)){
				
				if(sms.length()==4 && StringUtils.equals(sms, CONST.getAttr("reg"+mobile))){
					if(!user.isExistMobile(mobile)){ 
						
						// 开始判断推荐人
						int refId = 0; 
						if(Str.nb(referee) && CheckUtils.checkMoible(referee)){
							if(Str.ne(mobile, referee) && user.isExistMobile(referee)){
								refId = user.findByMobile(referee).getId();
							}else{
								renderJson(Json.error("推荐人未注册！"));
								return;
							}
						}
						
						// 开始注册用户 
						User u = new User();
						u.setMobile(mobile);
						u.setPassword(MD5Util.encrypt(password)); 
						u.setReferee(refId); 
						u.setCreateTime(new Date()); 
						u.setStatus("normal"); 
						u.setIsFund(0);
						u.setErrorCount(0);
						u.setLoginTime(new Date());
						u.setPopChannel(getPara("popChannel","0003"));
						u.setDownloadChannel(getPara("downloadChannel",Str.eq("iOS", type) ? "0002" : "0003"));
						u.setLoginType(type);
						u.setIsLunarCalendar(0);
						u.setRealName("");
						u.setBankCard("");
						u.setCertNum("");
						u.setAgentId(0);
						
						/** 	开始随机分配给在岗客服
						Random random = new Random();	
						String[] agents = CONST.find("ALLOT_AGENTS").split(",");
						if(agents.length>0) {
							u.setAgentId(Integer.valueOf(agents[random.nextInt(agents.length)]));
						}*/
						 
						if(u.save()){
							if(u.getReferee()>0) {
								// 插入推荐好友记录
								UserReferee uf = new UserReferee();
								uf.setUserId(u.getId());
								uf.setRefereeId(u.getReferee());
								uf.setCreateTime(u.getCreateTime());
								uf.setMobile(u.getMobile());
								uf.setRefereeMobile(referee);
								uf.setAmount(0.0);
								uf.save();
							}
							
							// 刷新用户token
							String token = app.refresh(u, type);
							setSessionAttr("token", token);
							CONST.removeAttr("reg"+mobile); 
							
							// 获取优惠券
							coupon.available(u.getId(), CouponRule.REG);
							
							// 日志记录
							log.build("注册", "用户注册", u.getId(), "user");
							
							// 需要加密
							if(aes==1) {
								u.setMobile(AES.encode(u.getMobile()));
							}
							
							renderJson(Json.ok("注册成功！", Data.put("token",token,"info",u, "tips",CONST.find("REG_TIPS"))));
						}else{
							renderJson(Json.error("数据保存失败！"));
						}
					}else{
						renderJson(Json.error("手机号已存在，请修改！"));
					}
				}else{
					renderJson(Json.error("手机验证码不正确！"));
				}
			}else{	
				renderJson(Json.error("手机号或密码格式不正确！"));
			}
		}else{	
			renderJson(Json.error("密码长度不可小于6位！"));
		}
	}

	/**
	 * 修改手机号
	 */
	public void modifyMobile() throws Exception {
		User u = getAttr("user");
		boolean type = Str.eq("app", getPara("type","app"));
		if(Str.nb(u.getCode())) {
			String code = DateUtil.getTimeStamp();
			Map<Object, Object> data = Gateway.form(type?"app/400101":"400101",  Data.put(
				"mchnt_txn_ssn",code, 
				"login_id",u.getCode(),
				"page_notify_url",CONST.URL+"/user/modifyMobileNotify",
				"sign","login_id,mchnt_cd,mchnt_txn_ssn,page_notify_url"
			));
			setAttr("data", data);
			render("/view/app/user/modifyMobile.html");
		}else{
			setAttr("token", getPara("token"));
			setAttr("mobile", u.getMobile());
			render("/view/app/user/mobileModify.html");
		}
	}
	
	/**
	 * 修改手机号
	 */
	public void ressetMobile() throws Exception {
		User u = getAttr("user");
		String sms = getPara("sms","");
		String mobile = getParaToInt("aes",1)==1?AES.decode(getPara("mobile","")):getPara("mobile","");

		if(user.isExistMobile(mobile)){ 
			if(CheckUtils.checkMoible(mobile)  && Str.eq(sms,CONST.getAttr("modifyMobileOld"+mobile))){
				String ticket = MD5Util.encrypt(String.valueOf(u.getId()));
				CONST.setAttr(u.getId()+"modifyMobileTicket", ticket);
				renderJson(Json.ok("短信验证码正确！", ticket));
			} else {
				renderJson(Json.error("短信验证码错误！"));
			}
		} else {
			renderJson(Json.error("该手机号不存在！"));
		}
	}
	
	/**
	 * 修改手机号
	 * @throws Exception 
	 */
	public void ressetMobileAdvance() throws Exception {
		User u = getAttr("user");
		String sms = getPara("sms","");
		String mobile = getParaToInt("aes",1)==1?AES.decode(getPara("mobile","")):getPara("mobile","");
		String ticket = getPara("ticket","");
		
		if(!user.isExistMobile(mobile)){ 
			if(Str.nb(ticket) && Str.eq(CONST.getAttr(u.getId()+"modifyMobileTicket"), ticket)){
				if(CheckUtils.checkMoible(mobile)  && StringUtils.equals(sms,CONST.getAttr("modifyMobileNew"+mobile))){
					user.refreshMobile(u.getMobile(),mobile);
					u.set("mobile", mobile).update();
					log.build("修改手机号", "用户修改手机号成功（平台）", u.getId(), "user");
					renderJson(Json.ok("新手机号修改成功！"));
				}else{
					renderJson(Json.error("新手机短信验证码错误！"));
				}
			}else{
				renderJson(Json.error("Ticket校验失败！"));
			}
		} else {
			renderJson(Json.error("该手机号已注册！"));
		}
	}
	
	/**
	 * 修改手机号回调
	 */
	@Clear
	public void modifyMobileNotify() {
		String code = getPara("login_id");
		if(Str.eq("0000", getPara("resp_code")) && Str.nb(code)) {
			User u = user.findByCode(code);
			String mobile1 = u.getMobile();
			String mobile2 = getPara("new_mobile");
			u.setMobile(mobile2).update();
			user.refreshMobile(mobile1,mobile2);
			removeSessionAttr("token");
			app.removeByMobile(mobile2,"app"); 
			log.build("设置", "用户设置手机号成功（富有）", u.getId(), "user");
		}
		render("/view/app/user/return.html");
	}
	
	/**
	 * 重置登陆密码
	 */
	@Clear
	public void ressetPassword() {
		int aes = getParaToInt("aes",1);
		String mobile = getPara("mobile","");
		String password = getPara("password","");
		String sms = getPara("sms");
		
		// AES解密
		if(aes==1) {
			mobile = AES.decode(mobile);
			password = AES.decode(password);
		}

		if(Str.nb(sms)){
			if(Str.nb(password) && CheckUtils.checkPassword(password)){
				User u = user.findByMobile(mobile);
				if(user.findByMobile(mobile)!=null){
					if(u!=null && Str.eq(sms, CONST.getAttr("ressetPassword"+mobile))){
						if(Str.ne(u.getStr("password"), MD5Util.encrypt(password))){
							u.set("password", MD5Util.encrypt(password)).setErrorCount(0).update();
							CONST.removeAttr("ressetPassword"+mobile);
							log.build("设置", "用户设置登陆密码成功", u.getId(), "user");
							renderJson(Json.ok("修改成功！"));
						}else{
							renderJson(Json.error("新密码不可与原密码一致！"));
						}
					}else{
						renderJson(Json.error("手机验证码不正确！"));
					}
				}else{
					renderJson(Json.error("该手机号未注册！"));
				}
			}else{	
				renderJson(Json.error("密码格式不正确！"));
			}
		}else{	
			renderJson(Json.error("验证码不可为空！"));
		}
	}
	
	/**
	 * 重置支付密码
	 */
	public void ressetPayPassword() {
		User u = getAttr("user");
		String type = getPara("type","app");
		// 检查用户是否已绑卡
		if(u.getIsBindBankCard()==1){
			Map<Object, Object> data = Gateway.form(Str.eq("app", type)?"/app/appResetPassWord":"/resetPassWord", Data.put(
				"mchnt_txn_ssn",DateUtil.getTimeStamp(),
				"login_id",u.getCode(),
				"busi_tp","3",
				"back_url",CONST.URL+"/app/page/user-return", 
				"sign","busi_tp,login_id,mchnt_cd,mchnt_txn_ssn"
			));
			setAttr("data", data);
			render("/view/app/user/ressetPayPassword.html");
		}else{
			renderJson(Json.error("用户未实名绑卡！"));
		}
	}
	
	/**
	 * 设置用户安全邮箱
	 * @throws Exception 
	 */
	public void setEmail() throws Exception {
		User u = getAttr("user");
		int aes = getParaToInt("aes",1);
		String email = aes==1?AES.decode(getPara("email","")):getPara("email","");
		String code = RandomCodeUtil.getCode();
		
		if(CheckUtils.checkEmail(email)) {
	        int res = MailUtil.sendEmail(new String[]{email}, "未了财富号安全中心-邮箱身份验证", "亲爱的用户：您好，本次请求的邮件码是："
	        		+code+"（为了保障您账号的安全性，请您尽快完成验证）如非本人操作，请忽略该邮件。祝使用愉快！");  
	        if(res>0){
	        	CONST.setAttr(email, code);
				log.build("设置安全邮箱", "获取验证码："+code, u.getId(), "");
	        	renderJson(Json.ok("验证邮件发送成功！"));
			}else{
	        	renderJson(Json.error("邮件发送失败！"));
			}  
        }else {
			renderJson(Json.error("邮箱格式错误！"));
		}
	}
	
	/**
	 * 设置用户安全邮箱.推进
	 * @throws Exception 
	 */
	public void setEmailAdvance() throws Exception {
		User u = getAttr("user");
		int aes = getParaToInt("aes",1);
		String email = aes==1?AES.decode(getPara("email","")):getPara("email","");
		String code = getPara("code"); 
		
		if(CheckUtils.checkEmail(email)) {
			if(Str.eq(code,CONST.getAttr(email))) {
				u.setEmail(email).setIsMailVerify(1).update();
				// Gateway.绑定认证信息---邮箱
				CONST.removeAttr(email);		
				log.build("绑定邮箱", "用户绑定邮箱成功", u.getId(), "user");
				renderJson(Json.ok("邮箱验证成功！"));
			} else {
				renderJson(Json.error("邮箱验证码错误！"));
			}
		} else {
			renderJson(Json.error("邮箱格式错误！"));
		}
	}
	
	/**
	 * 更新用户信息
	 * @throws Exception 
	 */
	@Clear
	public void update() throws Exception {	
		int id = getParaToInt("id",0);
		User u = User.me.findById(id);
		if(id>0 && u!=null){
			u.setStatus(getPara("status"))
				.setLoginType(getPara("loginType"))
				.setCreateTime(getParaToDate("createTime")).update();
		}
		renderJson(Json.ok("用户信息修改成功！"));
	}
	
	/**
	 * 根据ID获取用户信息
	 * @throws Exception 
	 */
	public void fullInfo() throws Exception {	
		User u = User.me.findById(getParaToInt("id",0));
		User referee = User.me.findById(u.getReferee());
		User agent = User.me.findById(u.getAgentId());
		u.put("referee", referee!=null?referee.getRealName():"");
		u.put("agent", agent!=null?agent.getRealName():"");
		u.refereshAmount();
		renderJson(Json.ok("信息获取成功！", Data.put("info", u)));
	}

	/**
	 * 修改用户基础信息
	 * @throws Exception 
	*/
	public void modifyInfo() throws Exception {	
		User u = User.me.findById(getParaToInt("id",0));
		if(u!=null) {
			u.setIsLunarCalendar(getParaToInt("isLunarCalendar",0)).update();
			renderJson(Json.ok("修改成功！"));
		}else {
			renderJson(Json.error("用户不存在！"));
		}
	} 
	
	/**
	 * 获取图形验证码
	 */
	@Clear 
	public void verifyCode() throws Exception {
		String mobile = getPara("mobile");
		if(CheckUtils.checkMoible(mobile)) {
			render(new MyCaptchaRender(mobile,60,22,4,true));
		}else {
			renderJson(Json.error("手机号码不正确！"));
		}
	}
	
	/**
	 * 微信分享
	 */
	public void share() throws Exception {
		String dateStr = CONST.getAttr("shareTimeExpires");
		String jsapi = ""; 
		if(Str.isBlank(dateStr) || Long.valueOf(DateUtil.getTimeStamp())-Long.valueOf(dateStr)>=0){
	        String res = Http.post("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxa46abff2e5dac6de&secret=b759ec5e165493bdd9a5507b7d2f1d1e");
	        res = Http.post("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+JSONObject.parseObject(res).getString("access_token")+"&type=jsapi");
	        jsapi = JSONObject.parseObject(res).getString("ticket");
	        CONST.setAttr("shareTimeExpires", String.valueOf(new Date().getTime()+7200000));
			CONST.setAttr("shareTimeExpiresApi", jsapi);
		} else {
			jsapi = CONST.getAttr("shareTimeExpiresApi");
		}
        Map<String, String> ret = WechatSign.sign(jsapi, "https://www.wlcfull.com/app/page/user-friendsInvite");
		renderJson(Json.ok("数据获取成功！",Data.put("appid","wxa46abff2e5dac6de","nonceStr",ret.get("nonceStr"),"sign",ret.get("signature"),"timestamp",ret.get("timestamp"))));
	}
}
 